﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
    internal class Cache<TKey, TValue>
    {
        private object _lock = new object();
        private Func<TKey, TValue> missingAction;
        private Dictionary<TKey, TValue> cache = new Dictionary<TKey, TValue>();

        public Cache(Func<TKey, TValue> missingAction)
        {
            this.missingAction = missingAction;
        }

        public TValue Get(TKey key)
        {
            TValue value;
            if (!cache.TryGetValue(key, out value))
            {
                lock (_lock)
                {
                    if (!cache.ContainsKey(key))
                    {
                        value = missingAction(key);
                        cache.Add(key, value);
                    }
                    else
                    {
                        value = cache[key];
                    }
                }
            }

            return value;
        }

        public void Invalidate(TKey key)
        {
            lock (_lock)
            {
                cache.Remove(key);
            }
        }
    }
}
